from django.db import models
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from apps.projects.models import Project
from apps.accounts.models import College


class SubProject(models.Model):
    """子项目模型"""
    STATUS_CHOICES = [
        ('initial', '初始'),
        ('approved', '立项通过'),
        ('mid_check', '中期检查通过'),
        ('completed', '结项完成'),
    ]
    
    project = models.ForeignKey(
        Project, 
        on_delete=models.CASCADE, 
        verbose_name='所属项目',
        help_text='此子项目所属的主项目'
    )
    name = models.CharField(
        max_length=200, 
        verbose_name='子项目名称',
        help_text='子项目的完整名称'
    )
    description = models.TextField(
        verbose_name='子项目描述',
        help_text='详细描述子项目内容和目标'
    )
    manager = models.CharField(
        max_length=100, 
        verbose_name='项目负责人',
        help_text='负责此子项目的人员姓名'
    )
    team_members = models.TextField(
        verbose_name='团队成员',
        help_text='参与此子项目的团队成员，多个成员用逗号分隔'
    )
    used_budget = models.DecimalField(
        max_digits=10, 
        decimal_places=2, 
        verbose_name='使用经费',
        help_text='此子项目使用的经费金额（单位：元）'
    )
    status = models.CharField(
        max_length=20, 
        choices=STATUS_CHOICES, 
        default='initial', 
        verbose_name='项目状态'
    )
    completion_date = models.DateTimeField(
        null=True, 
        blank=True, 
        verbose_name='完成时间',
        help_text='项目完成的具体时间'
    )
    
    # 新增三个时间字段
    project_start_date = models.DateField(
        null=True, 
        blank=True, 
        verbose_name='立项时间',
        help_text='子项目正式立项的日期'
    )
    midterm_check_date = models.DateField(
        null=True, 
        blank=True, 
        verbose_name='中期检查时间',
        help_text='子项目中期检查的日期'
    )
    project_end_date = models.DateField(
        null=True, 
        blank=True, 
        verbose_name='结项时间',
        help_text='子项目正式结项的日期'
    )
    
    college = models.ForeignKey(
        College,
        on_delete=models.CASCADE,
        related_name='subprojects',
        verbose_name='所属二级学院',
        help_text='子项目所属的二级学院'
    )
    created_by = models.ForeignKey(
        User, 
        on_delete=models.CASCADE, 
        verbose_name='创建者',
        help_text='创建此子项目的用户'
    )
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    class Meta:
        verbose_name = '子项目'
        verbose_name_plural = '子项目'
        ordering = ['-created_at']
        
    def __str__(self):
        return f"{self.project.name} - {self.name}"
    
    def clean(self):
        """数据验证"""
        super().clean()
        
        # 验证经费为正数
        if self.used_budget and self.used_budget <= 0:
            raise ValidationError({
                'used_budget': '使用经费必须大于0'
            })
        
        # 验证经费不超过项目总经费
        if self.project and self.used_budget:
            # 计算其他子项目已使用的经费
            other_subprojects_budget = self.project.subproject_set.exclude(
                pk=self.pk
            ).aggregate(
                total=models.Sum('used_budget')
            )['total'] or 0
            
            total_used = other_subprojects_budget + self.used_budget
            
            if total_used > self.project.budget:
                remaining = self.project.budget - other_subprojects_budget
                raise ValidationError({
                    'used_budget': f'经费超限！项目剩余经费为 {remaining:.2f} 元'
                })
        
        # 验证完成时间
        if self.status == 'completed' and not self.completion_date:
            raise ValidationError({
                'completion_date': '项目状态为已完成时，必须填写完成时间'
            })
    
    @property
    def college_name(self):
        """获取学院名称（兼容性属性）"""
        return self.college.name if self.college else None
    
    @property
    def status_color(self):
        """状态颜色"""
        color_map = {
            'initial': 'secondary',
            'approved': 'primary',
            'mid_check': 'warning',
            'completed': 'success',
        }
        return color_map.get(self.status, 'secondary')
    
    @property
    def is_completed(self):
        """是否已完成"""
        return self.status == 'completed'
    
    @property
    def can_edit_status(self):
        """是否可以编辑状态（管理员权限）"""
        return True  # 在视图中进行权限控制
    
    def get_team_members_list(self):
        """获取团队成员列表"""
        if not self.team_members:
            return []
        return [member.strip() for member in self.team_members.split(',') if member.strip()]
    
    def get_progress_percentage(self):
        """获取进度百分比"""
        progress_map = {
            'initial': 0,
            'approved': 25,
            'mid_check': 75,
            'completed': 100,
        }
        return progress_map.get(self.status, 0)
    
    def save(self, *args, **kwargs):
        """保存时自动设置完成时间"""
        if self.status == 'completed' and not self.completion_date:
            from django.utils import timezone
            self.completion_date = timezone.now()
        elif self.status != 'completed':
            self.completion_date = None
        
        super().save(*args, **kwargs)